
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_Hans">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Advanced testing topics &#8212; Django 3.2.6.dev 文档</title>
    <link rel="stylesheet" href="../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../_static/doctools.js"></script>
    <script type="text/javascript" src="../../_static/language_data.js"></script>
    <link rel="index" title="索引" href="../../genindex.html" />
    <link rel="search" title="搜索" href="../../search.html" />
    <link rel="next" title="User authentication in Django" href="../auth/index.html" />
    <link rel="prev" title="Testing tools" href="tools.html" />



 
<script src="../../templatebuiltins.js"></script>
<script>
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);</script>

  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../../index.html">Django 3.2.6.dev 文档</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../../index.html">Home</a>  |
        <a title="Table of contents" href="../../contents.html">Table of contents</a>  |
        <a title="Global index" href="../../genindex.html">Index</a>  |
        <a title="Module index" href="../../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="tools.html" title="Testing tools">previous</a>
     |
    <a href="../index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="../auth/index.html" title="User authentication in Django">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="topics-testing-advanced">
            
  <div class="section" id="s-advanced-testing-topics">
<span id="advanced-testing-topics"></span><h1>Advanced testing topics<a class="headerlink" href="#advanced-testing-topics" title="永久链接至标题">¶</a></h1>
<div class="section" id="s-the-request-factory">
<span id="the-request-factory"></span><h2>The request factory<a class="headerlink" href="#the-request-factory" title="永久链接至标题">¶</a></h2>
<dl class="class">
<dt id="django.test.RequestFactory">
<em class="property">class </em><code class="descname">RequestFactory</code><a class="headerlink" href="#django.test.RequestFactory" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>The <a class="reference internal" href="#django.test.RequestFactory" title="django.test.RequestFactory"><code class="xref py py-class docutils literal notranslate"><span class="pre">RequestFactory</span></code></a> shares the same API as
the test client. However, instead of behaving like a browser, the
RequestFactory provides a way to generate a request instance that can
be used as the first argument to any view. This means you can test a
view function the same way as you would test any other function -- as
a black box, with exactly known inputs, testing for specific outputs.</p>
<p>The API for the <a class="reference internal" href="#django.test.RequestFactory" title="django.test.RequestFactory"><code class="xref py py-class docutils literal notranslate"><span class="pre">RequestFactory</span></code></a> is a slightly
restricted subset of the test client API:</p>
<ul class="simple">
<li>It only has access to the HTTP methods <a class="reference internal" href="tools.html#django.test.Client.get" title="django.test.Client.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code></a>,
<a class="reference internal" href="tools.html#django.test.Client.post" title="django.test.Client.post"><code class="xref py py-meth docutils literal notranslate"><span class="pre">post()</span></code></a>, <a class="reference internal" href="tools.html#django.test.Client.put" title="django.test.Client.put"><code class="xref py py-meth docutils literal notranslate"><span class="pre">put()</span></code></a>,
<a class="reference internal" href="tools.html#django.test.Client.delete" title="django.test.Client.delete"><code class="xref py py-meth docutils literal notranslate"><span class="pre">delete()</span></code></a>, <a class="reference internal" href="tools.html#django.test.Client.head" title="django.test.Client.head"><code class="xref py py-meth docutils literal notranslate"><span class="pre">head()</span></code></a>,
<a class="reference internal" href="tools.html#django.test.Client.options" title="django.test.Client.options"><code class="xref py py-meth docutils literal notranslate"><span class="pre">options()</span></code></a>, and <a class="reference internal" href="tools.html#django.test.Client.trace" title="django.test.Client.trace"><code class="xref py py-meth docutils literal notranslate"><span class="pre">trace()</span></code></a>.</li>
<li>These methods accept all the same arguments <em>except</em> for
<code class="docutils literal notranslate"><span class="pre">follow</span></code>. Since this is just a factory for producing
requests, it's up to you to handle the response.</li>
<li>It does not support middleware. Session and authentication
attributes must be supplied by the test itself if required
for the view to function properly.</li>
</ul>
<div class="section" id="s-example">
<span id="example"></span><h3>Example<a class="headerlink" href="#example" title="永久链接至标题">¶</a></h3>
<p>The following is a unit test using the request factory:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.contrib.auth.models</span> <span class="kn">import</span> <span class="n">AnonymousUser</span><span class="p">,</span> <span class="n">User</span>
<span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">RequestFactory</span><span class="p">,</span> <span class="n">TestCase</span>

<span class="kn">from</span> <span class="nn">.views</span> <span class="kn">import</span> <span class="n">MyView</span><span class="p">,</span> <span class="n">my_view</span>

<span class="k">class</span> <span class="nc">SimpleTest</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">setUp</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="c1"># Every test needs access to the request factory.</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">factory</span> <span class="o">=</span> <span class="n">RequestFactory</span><span class="p">()</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">user</span> <span class="o">=</span> <span class="n">User</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create_user</span><span class="p">(</span>
            <span class="n">username</span><span class="o">=</span><span class="s1">&#39;jacob&#39;</span><span class="p">,</span> <span class="n">email</span><span class="o">=</span><span class="s1">&#39;jacob@…&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s1">&#39;top_secret&#39;</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">test_details</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="c1"># Create an instance of a GET request.</span>
        <span class="n">request</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">factory</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;/customer/details&#39;</span><span class="p">)</span>

        <span class="c1"># Recall that middleware are not supported. You can simulate a</span>
        <span class="c1"># logged-in user by setting request.user manually.</span>
        <span class="n">request</span><span class="o">.</span><span class="n">user</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">user</span>

        <span class="c1"># Or you can simulate an anonymous user by setting request.user to</span>
        <span class="c1"># an AnonymousUser instance.</span>
        <span class="n">request</span><span class="o">.</span><span class="n">user</span> <span class="o">=</span> <span class="n">AnonymousUser</span><span class="p">()</span>

        <span class="c1"># Test my_view() as if it were deployed at /customer/details</span>
        <span class="n">response</span> <span class="o">=</span> <span class="n">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">)</span>
        <span class="c1"># Use this syntax for class-based views.</span>
        <span class="n">response</span> <span class="o">=</span> <span class="n">MyView</span><span class="o">.</span><span class="n">as_view</span><span class="p">()(</span><span class="n">request</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">status_code</span><span class="p">,</span> <span class="mi">200</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="s-asyncrequestfactory">
<span id="asyncrequestfactory"></span><h3>AsyncRequestFactory<a class="headerlink" href="#asyncrequestfactory" title="永久链接至标题">¶</a></h3>
<p><code class="docutils literal notranslate"><span class="pre">RequestFactory</span></code> creates WSGI-like requests. If you want to create ASGI-like
requests, including having a correct ASGI <code class="docutils literal notranslate"><span class="pre">scope</span></code>, you can instead use
<code class="docutils literal notranslate"><span class="pre">django.test.AsyncRequestFactory</span></code>.</p>
<p>This class is directly API-compatible with <code class="docutils literal notranslate"><span class="pre">RequestFactory</span></code>, with the only
difference being that it returns <code class="docutils literal notranslate"><span class="pre">ASGIRequest</span></code> instances rather than
<code class="docutils literal notranslate"><span class="pre">WSGIRequest</span></code> instances. All of its methods are still synchronous callables.</p>
</div>
</div>
<div class="section" id="s-testing-class-based-views">
<span id="testing-class-based-views"></span><h2>Testing class-based views<a class="headerlink" href="#testing-class-based-views" title="永久链接至标题">¶</a></h2>
<p>In order to test class-based views outside of the request/response cycle you
must ensure that they are configured correctly, by calling
<a class="reference internal" href="../../ref/class-based-views/base.html#django.views.generic.base.View.setup" title="django.views.generic.base.View.setup"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setup()</span></code></a> after instantiation.</p>
<p>For example, assuming the following class-based view:</p>
<div class="literal-block-wrapper docutils container" id="id1">
<div class="code-block-caption"><span class="caption-text">views.py</span><a class="headerlink" href="#id1" title="永久链接至代码">¶</a></div>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.views.generic</span> <span class="kn">import</span> <span class="n">TemplateView</span>


<span class="k">class</span> <span class="nc">HomeView</span><span class="p">(</span><span class="n">TemplateView</span><span class="p">):</span>
    <span class="n">template_name</span> <span class="o">=</span> <span class="s1">&#39;myapp/home.html&#39;</span>

    <span class="k">def</span> <span class="nf">get_context_data</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="n">kwargs</span><span class="p">[</span><span class="s1">&#39;environment&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;Production&#39;</span>
        <span class="k">return</span> <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="n">get_context_data</span><span class="p">(</span><span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
</pre></div>
</div>
</div>
<p>You may directly test the <code class="docutils literal notranslate"><span class="pre">get_context_data()</span></code> method by first instantiating
the view, then passing a <code class="docutils literal notranslate"><span class="pre">request</span></code> to <code class="docutils literal notranslate"><span class="pre">setup()</span></code>, before proceeding with
your test's code:</p>
<div class="literal-block-wrapper docutils container" id="id2">
<div class="code-block-caption"><span class="caption-text">tests.py</span><a class="headerlink" href="#id2" title="永久链接至代码">¶</a></div>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">RequestFactory</span><span class="p">,</span> <span class="n">TestCase</span>
<span class="kn">from</span> <span class="nn">.views</span> <span class="kn">import</span> <span class="n">HomeView</span>


<span class="k">class</span> <span class="nc">HomePageTest</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">test_environment_set_in_context</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">request</span> <span class="o">=</span> <span class="n">RequestFactory</span><span class="p">()</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;/&#39;</span><span class="p">)</span>
        <span class="n">view</span> <span class="o">=</span> <span class="n">HomeView</span><span class="p">()</span>
        <span class="n">view</span><span class="o">.</span><span class="n">setup</span><span class="p">(</span><span class="n">request</span><span class="p">)</span>

        <span class="n">context</span> <span class="o">=</span> <span class="n">view</span><span class="o">.</span><span class="n">get_context_data</span><span class="p">()</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertIn</span><span class="p">(</span><span class="s1">&#39;environment&#39;</span><span class="p">,</span> <span class="n">context</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="s-tests-and-multiple-host-names">
<span id="s-topics-testing-advanced-multiple-hosts"></span><span id="tests-and-multiple-host-names"></span><span id="topics-testing-advanced-multiple-hosts"></span><h2>Tests and multiple host names<a class="headerlink" href="#tests-and-multiple-host-names" title="永久链接至标题">¶</a></h2>
<p>The <a class="reference internal" href="../../ref/settings.html#std:setting-ALLOWED_HOSTS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">ALLOWED_HOSTS</span></code></a> setting is validated when running tests. This
allows the test client to differentiate between internal and external URLs.</p>
<p>Projects that support multitenancy or otherwise alter business logic based on
the request's host and use custom host names in tests must include those hosts
in <a class="reference internal" href="../../ref/settings.html#std:setting-ALLOWED_HOSTS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">ALLOWED_HOSTS</span></code></a>.</p>
<p>The first option to do so is to add the hosts to your settings file. For
example, the test suite for docs.djangoproject.com includes the following:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">TestCase</span>

<span class="k">class</span> <span class="nc">SearchFormTestCase</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">test_empty_get</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">response</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;/en/dev/search/&#39;</span><span class="p">,</span> <span class="n">HTTP_HOST</span><span class="o">=</span><span class="s1">&#39;docs.djangoproject.dev:8000&#39;</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">status_code</span><span class="p">,</span> <span class="mi">200</span><span class="p">)</span>
</pre></div>
</div>
<p>and the settings file includes a list of the domains supported by the project:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">ALLOWED_HOSTS</span> <span class="o">=</span> <span class="p">[</span>
    <span class="s1">&#39;www.djangoproject.dev&#39;</span><span class="p">,</span>
    <span class="s1">&#39;docs.djangoproject.dev&#39;</span><span class="p">,</span>
    <span class="o">...</span>
<span class="p">]</span>
</pre></div>
</div>
<p>Another option is to add the required hosts to <a class="reference internal" href="../../ref/settings.html#std:setting-ALLOWED_HOSTS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">ALLOWED_HOSTS</span></code></a> using
<a class="reference internal" href="tools.html#django.test.override_settings" title="django.test.override_settings"><code class="xref py py-meth docutils literal notranslate"><span class="pre">override_settings()</span></code></a> or
<a class="reference internal" href="tools.html#django.test.SimpleTestCase.modify_settings" title="django.test.SimpleTestCase.modify_settings"><code class="xref py py-attr docutils literal notranslate"><span class="pre">modify_settings()</span></code></a>. This option may be
preferable in standalone apps that can't package their own settings file or
for projects where the list of domains is not static (e.g., subdomains for
multitenancy). For example, you could write a test for the domain
<code class="docutils literal notranslate"><span class="pre">http://otherserver/</span></code> as follows:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">TestCase</span><span class="p">,</span> <span class="n">override_settings</span>

<span class="k">class</span> <span class="nc">MultiDomainTestCase</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span>
    <span class="nd">@override_settings</span><span class="p">(</span><span class="n">ALLOWED_HOSTS</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;otherserver&#39;</span><span class="p">])</span>
    <span class="k">def</span> <span class="nf">test_other_domain</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">response</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;http://otherserver/foo/bar/&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Disabling <a class="reference internal" href="../../ref/settings.html#std:setting-ALLOWED_HOSTS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">ALLOWED_HOSTS</span></code></a> checking (<code class="docutils literal notranslate"><span class="pre">ALLOWED_HOSTS</span> <span class="pre">=</span> <span class="pre">['*']</span></code>) when
running tests prevents the test client from raising a helpful error message if
you follow a redirect to an external URL.</p>
</div>
<div class="section" id="s-tests-and-multiple-databases">
<span id="s-topics-testing-advanced-multidb"></span><span id="tests-and-multiple-databases"></span><span id="topics-testing-advanced-multidb"></span><h2>Tests and multiple databases<a class="headerlink" href="#tests-and-multiple-databases" title="永久链接至标题">¶</a></h2>
<div class="section" id="s-testing-primary-replica-configurations">
<span id="s-topics-testing-primaryreplica"></span><span id="testing-primary-replica-configurations"></span><span id="topics-testing-primaryreplica"></span><h3>Testing primary/replica configurations<a class="headerlink" href="#testing-primary-replica-configurations" title="永久链接至标题">¶</a></h3>
<p>If you're testing a multiple database configuration with primary/replica
(referred to as master/slave by some databases) replication, this strategy of
creating test databases poses a problem.
When the test databases are created, there won't be any replication,
and as a result, data created on the primary won't be seen on the
replica.</p>
<p>To compensate for this, Django allows you to define that a database is
a <em>test mirror</em>. Consider the following (simplified) example database
configuration:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">DATABASES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;ENGINE&#39;</span><span class="p">:</span> <span class="s1">&#39;django.db.backends.mysql&#39;</span><span class="p">,</span>
        <span class="s1">&#39;NAME&#39;</span><span class="p">:</span> <span class="s1">&#39;myproject&#39;</span><span class="p">,</span>
        <span class="s1">&#39;HOST&#39;</span><span class="p">:</span> <span class="s1">&#39;dbprimary&#39;</span><span class="p">,</span>
         <span class="c1"># ... plus some other settings</span>
    <span class="p">},</span>
    <span class="s1">&#39;replica&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;ENGINE&#39;</span><span class="p">:</span> <span class="s1">&#39;django.db.backends.mysql&#39;</span><span class="p">,</span>
        <span class="s1">&#39;NAME&#39;</span><span class="p">:</span> <span class="s1">&#39;myproject&#39;</span><span class="p">,</span>
        <span class="s1">&#39;HOST&#39;</span><span class="p">:</span> <span class="s1">&#39;dbreplica&#39;</span><span class="p">,</span>
        <span class="s1">&#39;TEST&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s1">&#39;MIRROR&#39;</span><span class="p">:</span> <span class="s1">&#39;default&#39;</span><span class="p">,</span>
        <span class="p">},</span>
        <span class="c1"># ... plus some other settings</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>In this setup, we have two database servers: <code class="docutils literal notranslate"><span class="pre">dbprimary</span></code>, described
by the database alias <code class="docutils literal notranslate"><span class="pre">default</span></code>, and <code class="docutils literal notranslate"><span class="pre">dbreplica</span></code> described by the
alias <code class="docutils literal notranslate"><span class="pre">replica</span></code>. As you might expect, <code class="docutils literal notranslate"><span class="pre">dbreplica</span></code> has been configured
by the database administrator as a read replica of <code class="docutils literal notranslate"><span class="pre">dbprimary</span></code>, so in
normal activity, any write to <code class="docutils literal notranslate"><span class="pre">default</span></code> will appear on <code class="docutils literal notranslate"><span class="pre">replica</span></code>.</p>
<p>If Django created two independent test databases, this would break any
tests that expected replication to occur. However, the <code class="docutils literal notranslate"><span class="pre">replica</span></code>
database has been configured as a test mirror (using the
<a class="reference internal" href="../../ref/settings.html#std:setting-TEST_MIRROR"><code class="xref std std-setting docutils literal notranslate"><span class="pre">MIRROR</span></code></a> test setting), indicating that under
testing, <code class="docutils literal notranslate"><span class="pre">replica</span></code> should be treated as a mirror of <code class="docutils literal notranslate"><span class="pre">default</span></code>.</p>
<p>When the test environment is configured, a test version of <code class="docutils literal notranslate"><span class="pre">replica</span></code>
will <em>not</em> be created. Instead the connection to <code class="docutils literal notranslate"><span class="pre">replica</span></code>
will be redirected to point at <code class="docutils literal notranslate"><span class="pre">default</span></code>. As a result, writes to
<code class="docutils literal notranslate"><span class="pre">default</span></code> will appear on <code class="docutils literal notranslate"><span class="pre">replica</span></code> -- but because they are actually
the same database, not because there is data replication between the
two databases.</p>
</div>
<div class="section" id="s-controlling-creation-order-for-test-databases">
<span id="s-topics-testing-creation-dependencies"></span><span id="controlling-creation-order-for-test-databases"></span><span id="topics-testing-creation-dependencies"></span><h3>Controlling creation order for test databases<a class="headerlink" href="#controlling-creation-order-for-test-databases" title="永久链接至标题">¶</a></h3>
<p>By default, Django will assume all databases depend on the <code class="docutils literal notranslate"><span class="pre">default</span></code>
database and therefore always create the <code class="docutils literal notranslate"><span class="pre">default</span></code> database first.
However, no guarantees are made on the creation order of any other
databases in your test setup.</p>
<p>If your database configuration requires a specific creation order, you
can specify the dependencies that exist using the <a class="reference internal" href="../../ref/settings.html#std:setting-TEST_DEPENDENCIES"><code class="xref std std-setting docutils literal notranslate"><span class="pre">DEPENDENCIES</span></code></a> test setting. Consider the following (simplified)
example database configuration:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">DATABASES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="c1"># ... db settings</span>
        <span class="s1">&#39;TEST&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s1">&#39;DEPENDENCIES&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;diamonds&#39;</span><span class="p">],</span>
        <span class="p">},</span>
    <span class="p">},</span>
    <span class="s1">&#39;diamonds&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="c1"># ... db settings</span>
        <span class="s1">&#39;TEST&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s1">&#39;DEPENDENCIES&#39;</span><span class="p">:</span> <span class="p">[],</span>
        <span class="p">},</span>
    <span class="p">},</span>
    <span class="s1">&#39;clubs&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="c1"># ... db settings</span>
        <span class="s1">&#39;TEST&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s1">&#39;DEPENDENCIES&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;diamonds&#39;</span><span class="p">],</span>
        <span class="p">},</span>
    <span class="p">},</span>
    <span class="s1">&#39;spades&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="c1"># ... db settings</span>
        <span class="s1">&#39;TEST&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s1">&#39;DEPENDENCIES&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;diamonds&#39;</span><span class="p">,</span> <span class="s1">&#39;hearts&#39;</span><span class="p">],</span>
        <span class="p">},</span>
    <span class="p">},</span>
    <span class="s1">&#39;hearts&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="c1"># ... db settings</span>
        <span class="s1">&#39;TEST&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s1">&#39;DEPENDENCIES&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;diamonds&#39;</span><span class="p">,</span> <span class="s1">&#39;clubs&#39;</span><span class="p">],</span>
        <span class="p">},</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Under this configuration, the <code class="docutils literal notranslate"><span class="pre">diamonds</span></code> database will be created first,
as it is the only database alias without dependencies. The <code class="docutils literal notranslate"><span class="pre">default</span></code> and
<code class="docutils literal notranslate"><span class="pre">clubs</span></code> alias will be created next (although the order of creation of this
pair is not guaranteed), then <code class="docutils literal notranslate"><span class="pre">hearts</span></code>, and finally <code class="docutils literal notranslate"><span class="pre">spades</span></code>.</p>
<p>If there are any circular dependencies in the <a class="reference internal" href="../../ref/settings.html#std:setting-TEST_DEPENDENCIES"><code class="xref std std-setting docutils literal notranslate"><span class="pre">DEPENDENCIES</span></code></a> definition, an
<a class="reference internal" href="../../ref/exceptions.html#django.core.exceptions.ImproperlyConfigured" title="django.core.exceptions.ImproperlyConfigured"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImproperlyConfigured</span></code></a> exception will be raised.</p>
</div>
</div>
<div class="section" id="s-advanced-features-of-transactiontestcase">
<span id="advanced-features-of-transactiontestcase"></span><h2>Advanced features of <code class="docutils literal notranslate"><span class="pre">TransactionTestCase</span></code><a class="headerlink" href="#advanced-features-of-transactiontestcase" title="永久链接至标题">¶</a></h2>
<dl class="attribute">
<dt id="django.test.TransactionTestCase.available_apps">
<code class="descclassname">TransactionTestCase.</code><code class="descname">available_apps</code><a class="headerlink" href="#django.test.TransactionTestCase.available_apps" title="永久链接至目标">¶</a></dt>
<dd><div class="admonition warning">
<p class="first admonition-title">警告</p>
<p>This attribute is a private API. It may be changed or removed without
a deprecation period in the future, for instance to accommodate changes
in application loading.</p>
<p class="last">It's used to optimize Django's own test suite, which contains hundreds
of models but no relations between models in different applications.</p>
</div>
<p>By default, <code class="docutils literal notranslate"><span class="pre">available_apps</span></code> is set to <code class="docutils literal notranslate"><span class="pre">None</span></code>. After each test, Django
calls <a class="reference internal" href="../../ref/django-admin.html#django-admin-flush"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">flush</span></code></a> to reset the database state. This empties all tables
and emits the <a class="reference internal" href="../../ref/signals.html#django.db.models.signals.post_migrate" title="django.db.models.signals.post_migrate"><code class="xref py py-data docutils literal notranslate"><span class="pre">post_migrate</span></code></a> signal, which
recreates one content type and four permissions for each model. This
operation gets expensive proportionally to the number of models.</p>
<p>Setting <code class="docutils literal notranslate"><span class="pre">available_apps</span></code> to a list of applications instructs Django to
behave as if only the models from these applications were available. The
behavior of <code class="docutils literal notranslate"><span class="pre">TransactionTestCase</span></code> changes as follows:</p>
<ul class="simple">
<li><a class="reference internal" href="../../ref/signals.html#django.db.models.signals.post_migrate" title="django.db.models.signals.post_migrate"><code class="xref py py-data docutils literal notranslate"><span class="pre">post_migrate</span></code></a> is fired before each
test to create the content types and permissions for each model in
available apps, in case they're missing.</li>
<li>After each test, Django empties only tables corresponding to models in
available apps. However, at the database level, truncation may cascade to
related models in unavailable apps. Furthermore
<a class="reference internal" href="../../ref/signals.html#django.db.models.signals.post_migrate" title="django.db.models.signals.post_migrate"><code class="xref py py-data docutils literal notranslate"><span class="pre">post_migrate</span></code></a> isn't fired; it will be
fired by the next <code class="docutils literal notranslate"><span class="pre">TransactionTestCase</span></code>, after the correct set of
applications is selected.</li>
</ul>
<p>Since the database isn't fully flushed, if a test creates instances of
models not included in <code class="docutils literal notranslate"><span class="pre">available_apps</span></code>, they will leak and they may
cause unrelated tests to fail. Be careful with tests that use sessions;
the default session engine stores them in the database.</p>
<p>Since <a class="reference internal" href="../../ref/signals.html#django.db.models.signals.post_migrate" title="django.db.models.signals.post_migrate"><code class="xref py py-data docutils literal notranslate"><span class="pre">post_migrate</span></code></a> isn't emitted after
flushing the database, its state after a <code class="docutils literal notranslate"><span class="pre">TransactionTestCase</span></code> isn't the
same as after a <code class="docutils literal notranslate"><span class="pre">TestCase</span></code>: it's missing the rows created by listeners
to <a class="reference internal" href="../../ref/signals.html#django.db.models.signals.post_migrate" title="django.db.models.signals.post_migrate"><code class="xref py py-data docutils literal notranslate"><span class="pre">post_migrate</span></code></a>. Considering the
<a class="reference internal" href="overview.html#order-of-tests"><span class="std std-ref">order in which tests are executed</span></a>, this isn't an
issue, provided either all <code class="docutils literal notranslate"><span class="pre">TransactionTestCase</span></code> in a given test suite
declare <code class="docutils literal notranslate"><span class="pre">available_apps</span></code>, or none of them.</p>
<p><code class="docutils literal notranslate"><span class="pre">available_apps</span></code> is mandatory in Django's own test suite.</p>
</dd></dl>

<dl class="attribute">
<dt id="django.test.TransactionTestCase.reset_sequences">
<code class="descclassname">TransactionTestCase.</code><code class="descname">reset_sequences</code><a class="headerlink" href="#django.test.TransactionTestCase.reset_sequences" title="永久链接至目标">¶</a></dt>
<dd><p>Setting <code class="docutils literal notranslate"><span class="pre">reset_sequences</span> <span class="pre">=</span> <span class="pre">True</span></code> on a <code class="docutils literal notranslate"><span class="pre">TransactionTestCase</span></code> will make
sure sequences are always reset before the test run:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">TestsThatDependsOnPrimaryKeySequences</span><span class="p">(</span><span class="n">TransactionTestCase</span><span class="p">):</span>
    <span class="n">reset_sequences</span> <span class="o">=</span> <span class="kc">True</span>

    <span class="k">def</span> <span class="nf">test_animal_pk</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">lion</span> <span class="o">=</span> <span class="n">Animal</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s2">&quot;lion&quot;</span><span class="p">,</span> <span class="n">sound</span><span class="o">=</span><span class="s2">&quot;roar&quot;</span><span class="p">)</span>
        <span class="c1"># lion.pk is guaranteed to always be 1</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">lion</span><span class="o">.</span><span class="n">pk</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
</pre></div>
</div>
<p>Unless you are explicitly testing primary keys sequence numbers, it is
recommended that you do not hard code primary key values in tests.</p>
<p>Using <code class="docutils literal notranslate"><span class="pre">reset_sequences</span> <span class="pre">=</span> <span class="pre">True</span></code> will slow down the test, since the primary
key reset is a relatively expensive database operation.</p>
</dd></dl>

</div>
<div class="section" id="s-enforce-running-test-classes-sequentially">
<span id="s-topics-testing-enforce-run-sequentially"></span><span id="enforce-running-test-classes-sequentially"></span><span id="topics-testing-enforce-run-sequentially"></span><h2>Enforce running test classes sequentially<a class="headerlink" href="#enforce-running-test-classes-sequentially" title="永久链接至标题">¶</a></h2>
<p>If you have test classes that cannot be run in parallel (e.g. because they
share a common resource), you can use <code class="docutils literal notranslate"><span class="pre">django.test.testcases.SerializeMixin</span></code>
to run them sequentially. This mixin uses a filesystem <code class="docutils literal notranslate"><span class="pre">lockfile</span></code>.</p>
<p>For example, you can use <code class="docutils literal notranslate"><span class="pre">__file__</span></code> to determine that all test classes in the
same file that inherit from <code class="docutils literal notranslate"><span class="pre">SerializeMixin</span></code> will run sequentially:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">os</span>

<span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">TestCase</span>
<span class="kn">from</span> <span class="nn">django.test.testcases</span> <span class="kn">import</span> <span class="n">SerializeMixin</span>

<span class="k">class</span> <span class="nc">ImageTestCaseMixin</span><span class="p">(</span><span class="n">SerializeMixin</span><span class="p">):</span>
    <span class="n">lockfile</span> <span class="o">=</span> <span class="vm">__file__</span>

    <span class="k">def</span> <span class="nf">setUp</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">filename</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">temp_storage_dir</span><span class="p">,</span> <span class="s1">&#39;my_file.png&#39;</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">file</span> <span class="o">=</span> <span class="n">create_file</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">filename</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">RemoveImageTests</span><span class="p">(</span><span class="n">ImageTestCaseMixin</span><span class="p">,</span> <span class="n">TestCase</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">test_remove_image</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">os</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">filename</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertFalse</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">filename</span><span class="p">))</span>

<span class="k">class</span> <span class="nc">ResizeImageTests</span><span class="p">(</span><span class="n">ImageTestCaseMixin</span><span class="p">,</span> <span class="n">TestCase</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">test_resize_image</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">resize_image</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">file</span><span class="p">,</span> <span class="p">(</span><span class="mi">48</span><span class="p">,</span> <span class="mi">48</span><span class="p">))</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">get_image_size</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">file</span><span class="p">),</span> <span class="p">(</span><span class="mi">48</span><span class="p">,</span> <span class="mi">48</span><span class="p">))</span>
</pre></div>
</div>
</div>
<div class="section" id="s-using-the-django-test-runner-to-test-reusable-applications">
<span id="s-testing-reusable-applications"></span><span id="using-the-django-test-runner-to-test-reusable-applications"></span><span id="testing-reusable-applications"></span><h2>Using the Django test runner to test reusable applications<a class="headerlink" href="#using-the-django-test-runner-to-test-reusable-applications" title="永久链接至标题">¶</a></h2>
<p>If you are writing a <a class="reference internal" href="../../intro/reusable-apps.html"><span class="doc">reusable application</span></a>
you may want to use the Django test runner to run your own test suite
and thus benefit from the Django testing infrastructure.</p>
<p>A common practice is a <em>tests</em> directory next to the application code, with the
following structure:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">runtests</span><span class="o">.</span><span class="n">py</span>
<span class="n">polls</span><span class="o">/</span>
    <span class="fm">__init__</span><span class="o">.</span><span class="n">py</span>
    <span class="n">models</span><span class="o">.</span><span class="n">py</span>
    <span class="o">...</span>
<span class="n">tests</span><span class="o">/</span>
    <span class="fm">__init__</span><span class="o">.</span><span class="n">py</span>
    <span class="n">models</span><span class="o">.</span><span class="n">py</span>
    <span class="n">test_settings</span><span class="o">.</span><span class="n">py</span>
    <span class="n">tests</span><span class="o">.</span><span class="n">py</span>
</pre></div>
</div>
<p>Let's take a look inside a couple of those files:</p>
<div class="literal-block-wrapper docutils container" id="id3">
<div class="code-block-caption"><span class="caption-text">runtests.py</span><a class="headerlink" href="#id3" title="永久链接至代码">¶</a></div>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="ch">#!/usr/bin/env python</span>
<span class="kn">import</span> <span class="nn">os</span>
<span class="kn">import</span> <span class="nn">sys</span>

<span class="kn">import</span> <span class="nn">django</span>
<span class="kn">from</span> <span class="nn">django.conf</span> <span class="kn">import</span> <span class="n">settings</span>
<span class="kn">from</span> <span class="nn">django.test.utils</span> <span class="kn">import</span> <span class="n">get_runner</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s2">&quot;__main__&quot;</span><span class="p">:</span>
    <span class="n">os</span><span class="o">.</span><span class="n">environ</span><span class="p">[</span><span class="s1">&#39;DJANGO_SETTINGS_MODULE&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;tests.test_settings&#39;</span>
    <span class="n">django</span><span class="o">.</span><span class="n">setup</span><span class="p">()</span>
    <span class="n">TestRunner</span> <span class="o">=</span> <span class="n">get_runner</span><span class="p">(</span><span class="n">settings</span><span class="p">)</span>
    <span class="n">test_runner</span> <span class="o">=</span> <span class="n">TestRunner</span><span class="p">()</span>
    <span class="n">failures</span> <span class="o">=</span> <span class="n">test_runner</span><span class="o">.</span><span class="n">run_tests</span><span class="p">([</span><span class="s2">&quot;tests&quot;</span><span class="p">])</span>
    <span class="n">sys</span><span class="o">.</span><span class="n">exit</span><span class="p">(</span><span class="nb">bool</span><span class="p">(</span><span class="n">failures</span><span class="p">))</span>
</pre></div>
</div>
</div>
<p>This is the script that you invoke to run the test suite. It sets up the
Django environment, creates the test database and runs the tests.</p>
<p>For the sake of clarity, this example contains only the bare minimum
necessary to use the Django test runner. You may want to add
command-line options for controlling verbosity, passing in specific test
labels to run, etc.</p>
<div class="literal-block-wrapper docutils container" id="id4">
<div class="code-block-caption"><span class="caption-text">tests/test_settings.py</span><a class="headerlink" href="#id4" title="永久链接至代码">¶</a></div>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="n">SECRET_KEY</span> <span class="o">=</span> <span class="s1">&#39;fake-key&#39;</span>
<span class="n">INSTALLED_APPS</span> <span class="o">=</span> <span class="p">[</span>
    <span class="s2">&quot;tests&quot;</span><span class="p">,</span>
<span class="p">]</span>
</pre></div>
</div>
</div>
<p>This file contains the <a class="reference internal" href="../settings.html"><span class="doc">Django settings</span></a>
required to run your app's tests.</p>
<p>Again, this is a minimal example; your tests may require additional
settings to run.</p>
<p>Since the <em>tests</em> package is included in <a class="reference internal" href="../../ref/settings.html#std:setting-INSTALLED_APPS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">INSTALLED_APPS</span></code></a> when
running your tests, you can define test-only models in its <code class="docutils literal notranslate"><span class="pre">models.py</span></code>
file.</p>
</div>
<div class="section" id="s-using-different-testing-frameworks">
<span id="s-other-testing-frameworks"></span><span id="using-different-testing-frameworks"></span><span id="other-testing-frameworks"></span><h2>Using different testing frameworks<a class="headerlink" href="#using-different-testing-frameworks" title="永久链接至标题">¶</a></h2>
<p>Clearly, <a class="reference external" href="https://docs.python.org/3/library/unittest.html#module-unittest" title="(在 Python v3.9)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> is not the only Python testing framework. While Django
doesn't provide explicit support for alternative frameworks, it does provide a
way to invoke tests constructed for an alternative framework as if they were
normal Django tests.</p>
<p>When you run <code class="docutils literal notranslate"><span class="pre">./manage.py</span> <span class="pre">test</span></code>, Django looks at the <a class="reference internal" href="../../ref/settings.html#std:setting-TEST_RUNNER"><code class="xref std std-setting docutils literal notranslate"><span class="pre">TEST_RUNNER</span></code></a>
setting to determine what to do. By default, <a class="reference internal" href="../../ref/settings.html#std:setting-TEST_RUNNER"><code class="xref std std-setting docutils literal notranslate"><span class="pre">TEST_RUNNER</span></code></a> points to
<code class="docutils literal notranslate"><span class="pre">'django.test.runner.DiscoverRunner'</span></code>. This class defines the default Django
testing behavior. This behavior involves:</p>
<ol class="arabic simple">
<li>Performing global pre-test setup.</li>
<li>Looking for tests in any file below the current directory whose name matches
the pattern <code class="docutils literal notranslate"><span class="pre">test*.py</span></code>.</li>
<li>Creating the test databases.</li>
<li>Running <code class="docutils literal notranslate"><span class="pre">migrate</span></code> to install models and initial data into the test
databases.</li>
<li>Running the <a class="reference internal" href="../checks.html"><span class="doc">system checks</span></a>.</li>
<li>Running the tests that were found.</li>
<li>Destroying the test databases.</li>
<li>Performing global post-test teardown.</li>
</ol>
<p>If you define your own test runner class and point <a class="reference internal" href="../../ref/settings.html#std:setting-TEST_RUNNER"><code class="xref std std-setting docutils literal notranslate"><span class="pre">TEST_RUNNER</span></code></a> at
that class, Django will execute your test runner whenever you run
<code class="docutils literal notranslate"><span class="pre">./manage.py</span> <span class="pre">test</span></code>. In this way, it is possible to use any test framework
that can be executed from Python code, or to modify the Django test execution
process to satisfy whatever testing requirements you may have.</p>
<div class="section" id="s-defining-a-test-runner">
<span id="s-topics-testing-test-runner"></span><span id="defining-a-test-runner"></span><span id="topics-testing-test-runner"></span><h3>Defining a test runner<a class="headerlink" href="#defining-a-test-runner" title="永久链接至标题">¶</a></h3>
<p>A test runner is a class defining a <code class="docutils literal notranslate"><span class="pre">run_tests()</span></code> method. Django ships
with a <code class="docutils literal notranslate"><span class="pre">DiscoverRunner</span></code> class that defines the default Django testing
behavior. This class defines the <code class="docutils literal notranslate"><span class="pre">run_tests()</span></code> entry point, plus a
selection of other methods that are used by <code class="docutils literal notranslate"><span class="pre">run_tests()</span></code> to set up, execute
and tear down the test suite.</p>
<dl class="class">
<dt id="django.test.runner.DiscoverRunner">
<em class="property">class </em><code class="descname">DiscoverRunner</code>(<em>pattern='test*.py'</em>, <em>top_level=None</em>, <em>verbosity=1</em>, <em>interactive=True</em>, <em>failfast=False</em>, <em>keepdb=False</em>, <em>reverse=False</em>, <em>debug_mode=False</em>, <em>debug_sql=False</em>, <em>parallel=0</em>, <em>tags=None</em>, <em>exclude_tags=None</em>, <em>test_name_patterns=None</em>, <em>pdb=False</em>, <em>buffer=False</em>, <em>enable_faulthandler=True</em>, <em>timing=True</em>, <em>**kwargs</em>)<a class="headerlink" href="#django.test.runner.DiscoverRunner" title="永久链接至目标">¶</a></dt>
<dd><p><code class="docutils literal notranslate"><span class="pre">DiscoverRunner</span></code> will search for tests in any file matching <code class="docutils literal notranslate"><span class="pre">pattern</span></code>.</p>
<p><code class="docutils literal notranslate"><span class="pre">top_level</span></code> can be used to specify the directory containing your
top-level Python modules. Usually Django can figure this out automatically,
so it's not necessary to specify this option. If specified, it should
generally be the directory containing your <code class="docutils literal notranslate"><span class="pre">manage.py</span></code> file.</p>
<p><code class="docutils literal notranslate"><span class="pre">verbosity</span></code> determines the amount of notification and debug information
that will be printed to the console; <code class="docutils literal notranslate"><span class="pre">0</span></code> is no output, <code class="docutils literal notranslate"><span class="pre">1</span></code> is normal
output, and <code class="docutils literal notranslate"><span class="pre">2</span></code> is verbose output.</p>
<p>If <code class="docutils literal notranslate"><span class="pre">interactive</span></code> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, the test suite has permission to ask the
user for instructions when the test suite is executed. An example of this
behavior would be asking for permission to delete an existing test
database. If <code class="docutils literal notranslate"><span class="pre">interactive</span></code> is <code class="docutils literal notranslate"><span class="pre">False</span></code>, the test suite must be able to
run without any manual intervention.</p>
<p>If <code class="docutils literal notranslate"><span class="pre">failfast</span></code> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, the test suite will stop running after the
first test failure is detected.</p>
<p>If <code class="docutils literal notranslate"><span class="pre">keepdb</span></code> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, the test suite will use the existing database,
or create one if necessary. If <code class="docutils literal notranslate"><span class="pre">False</span></code>, a new database will be created,
prompting the user to remove the existing one, if present.</p>
<p>If <code class="docutils literal notranslate"><span class="pre">reverse</span></code> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, test cases will be executed in the opposite
order. This could be useful to debug tests that aren't properly isolated
and have side effects. <a class="reference internal" href="overview.html#order-of-tests"><span class="std std-ref">Grouping by test class</span></a> is
preserved when using this option.</p>
<p><code class="docutils literal notranslate"><span class="pre">debug_mode</span></code> specifies what the <a class="reference internal" href="../../ref/settings.html#std:setting-DEBUG"><code class="xref std std-setting docutils literal notranslate"><span class="pre">DEBUG</span></code></a> setting should be
set to prior to running tests.</p>
<p><code class="docutils literal notranslate"><span class="pre">parallel</span></code> specifies the number of processes.  If <code class="docutils literal notranslate"><span class="pre">parallel</span></code> is greater
than <code class="docutils literal notranslate"><span class="pre">1</span></code>, the test suite will run in <code class="docutils literal notranslate"><span class="pre">parallel</span></code> processes. If there are
fewer test cases than configured processes, Django will reduce the number
of processes accordingly. Each process gets its own database. This option
requires the third-party <code class="docutils literal notranslate"><span class="pre">tblib</span></code> package to display tracebacks correctly.</p>
<p><code class="docutils literal notranslate"><span class="pre">tags</span></code> can be used to specify a set of <a class="reference internal" href="tools.html#topics-tagging-tests"><span class="std std-ref">tags for filtering tests</span></a>. May be combined with <code class="docutils literal notranslate"><span class="pre">exclude_tags</span></code>.</p>
<p><code class="docutils literal notranslate"><span class="pre">exclude_tags</span></code> can be used to specify a set of
<a class="reference internal" href="tools.html#topics-tagging-tests"><span class="std std-ref">tags for excluding tests</span></a>. May be combined
with <code class="docutils literal notranslate"><span class="pre">tags</span></code>.</p>
<p>If <code class="docutils literal notranslate"><span class="pre">debug_sql</span></code> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, failing test cases will output SQL queries
logged to the <a class="reference internal" href="../logging.html#django-db-logger"><span class="std std-ref">django.db.backends logger</span></a> as well
as the traceback. If <code class="docutils literal notranslate"><span class="pre">verbosity</span></code> is <code class="docutils literal notranslate"><span class="pre">2</span></code>, then queries in all tests are
output.</p>
<p><code class="docutils literal notranslate"><span class="pre">test_name_patterns</span></code> can be used to specify a set of patterns for
filtering test methods and classes by their names.</p>
<p>If <code class="docutils literal notranslate"><span class="pre">pdb</span></code> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, a debugger (<code class="docutils literal notranslate"><span class="pre">pdb</span></code> or <code class="docutils literal notranslate"><span class="pre">ipdb</span></code>) will be spawned at
each test error or failure.</p>
<p>If <code class="docutils literal notranslate"><span class="pre">buffer</span></code> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, outputs from passing tests will be discarded.</p>
<p>If <code class="docutils literal notranslate"><span class="pre">enable_faulthandler</span></code> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, <a class="reference external" href="https://docs.python.org/3/library/faulthandler.html#module-faulthandler" title="(在 Python v3.9)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">faulthandler</span></code></a> will be
enabled.</p>
<p>If <code class="docutils literal notranslate"><span class="pre">timing</span></code> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, test timings, including database setup and total
run time, will be shown.</p>
<p>Django may, from time to time, extend the capabilities of the test runner
by adding new arguments. The <code class="docutils literal notranslate"><span class="pre">**kwargs</span></code> declaration allows for this
expansion. If you subclass <code class="docutils literal notranslate"><span class="pre">DiscoverRunner</span></code> or write your own test
runner, ensure it accepts <code class="docutils literal notranslate"><span class="pre">**kwargs</span></code>.</p>
<p>Your test runner may also define additional command-line options.
Create or override an <code class="docutils literal notranslate"><span class="pre">add_arguments(cls,</span> <span class="pre">parser)</span></code> class method and add
custom arguments by calling <code class="docutils literal notranslate"><span class="pre">parser.add_argument()</span></code> inside the method, so
that the <a class="reference internal" href="../../ref/django-admin.html#django-admin-test"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">test</span></code></a> command will be able to use those arguments.</p>
<div class="versionadded">
<span class="title">New in Django 3.1:</span> <p>The <code class="docutils literal notranslate"><span class="pre">buffer</span></code> argument was added.</p>
</div>
<div class="versionadded">
<span class="title">New in Django 3.2:</span> <p>The <code class="docutils literal notranslate"><span class="pre">enable_faulthandler</span></code> and <code class="docutils literal notranslate"><span class="pre">timing</span></code> arguments were added.</p>
</div>
</dd></dl>

<div class="section" id="s-attributes">
<span id="attributes"></span><h4>Attributes<a class="headerlink" href="#attributes" title="永久链接至标题">¶</a></h4>
<dl class="attribute">
<dt id="django.test.runner.DiscoverRunner.test_suite">
<code class="descclassname">DiscoverRunner.</code><code class="descname">test_suite</code><a class="headerlink" href="#django.test.runner.DiscoverRunner.test_suite" title="永久链接至目标">¶</a></dt>
<dd><p>The class used to build the test suite. By default it is set to
<code class="docutils literal notranslate"><span class="pre">unittest.TestSuite</span></code>. This can be overridden if you wish to implement
different logic for collecting tests.</p>
</dd></dl>

<dl class="attribute">
<dt id="django.test.runner.DiscoverRunner.test_runner">
<code class="descclassname">DiscoverRunner.</code><code class="descname">test_runner</code><a class="headerlink" href="#django.test.runner.DiscoverRunner.test_runner" title="永久链接至目标">¶</a></dt>
<dd><p>This is the class of the low-level test runner which is used to execute
the individual tests and format the results. By default it is set to
<code class="docutils literal notranslate"><span class="pre">unittest.TextTestRunner</span></code>. Despite the unfortunate similarity in
naming conventions, this is not the same type of class as
<code class="docutils literal notranslate"><span class="pre">DiscoverRunner</span></code>, which covers a broader set of responsibilities. You
can override this attribute to modify the way tests are run and reported.</p>
</dd></dl>

<dl class="attribute">
<dt id="django.test.runner.DiscoverRunner.test_loader">
<code class="descclassname">DiscoverRunner.</code><code class="descname">test_loader</code><a class="headerlink" href="#django.test.runner.DiscoverRunner.test_loader" title="永久链接至目标">¶</a></dt>
<dd><p>This is the class that loads tests, whether from TestCases or modules or
otherwise and bundles them into test suites for the runner to execute.
By default it is set to <code class="docutils literal notranslate"><span class="pre">unittest.defaultTestLoader</span></code>. You can override
this attribute if your tests are going to be loaded in unusual ways.</p>
</dd></dl>

</div>
<div class="section" id="s-methods">
<span id="methods"></span><h4>Methods<a class="headerlink" href="#methods" title="永久链接至标题">¶</a></h4>
<dl class="method">
<dt id="django.test.runner.DiscoverRunner.run_tests">
<code class="descclassname">DiscoverRunner.</code><code class="descname">run_tests</code>(<em>test_labels</em>, <em>extra_tests=None</em>, <em>**kwargs</em>)<a class="headerlink" href="#django.test.runner.DiscoverRunner.run_tests" title="永久链接至目标">¶</a></dt>
<dd><p>Run the test suite.</p>
<p><code class="docutils literal notranslate"><span class="pre">test_labels</span></code> allows you to specify which tests to run and supports
several formats (see <a class="reference internal" href="#django.test.runner.DiscoverRunner.build_suite" title="django.test.runner.DiscoverRunner.build_suite"><code class="xref py py-meth docutils literal notranslate"><span class="pre">DiscoverRunner.build_suite()</span></code></a> for a list of
supported formats).</p>
<p><code class="docutils literal notranslate"><span class="pre">extra_tests</span></code> is a list of extra <code class="docutils literal notranslate"><span class="pre">TestCase</span></code> instances to add to the
suite that is executed by the test runner. These extra tests are run
in addition to those discovered in the modules listed in <code class="docutils literal notranslate"><span class="pre">test_labels</span></code>.</p>
<p>This method should return the number of tests that failed.</p>
</dd></dl>

<dl class="classmethod">
<dt id="django.test.runner.DiscoverRunner.add_arguments">
<em class="property">classmethod </em><code class="descclassname">DiscoverRunner.</code><code class="descname">add_arguments</code>(<em>parser</em>)<a class="headerlink" href="#django.test.runner.DiscoverRunner.add_arguments" title="永久链接至目标">¶</a></dt>
<dd><p>Override this class method to add custom arguments accepted by the
<a class="reference internal" href="../../ref/django-admin.html#django-admin-test"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">test</span></code></a> management command. See
<a class="reference external" href="https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.add_argument" title="(在 Python v3.9)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">argparse.ArgumentParser.add_argument()</span></code></a> for details about adding
arguments to a parser.</p>
</dd></dl>

<dl class="method">
<dt id="django.test.runner.DiscoverRunner.setup_test_environment">
<code class="descclassname">DiscoverRunner.</code><code class="descname">setup_test_environment</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.test.runner.DiscoverRunner.setup_test_environment" title="永久链接至目标">¶</a></dt>
<dd><p>Sets up the test environment by calling
<a class="reference internal" href="#django.test.utils.setup_test_environment" title="django.test.utils.setup_test_environment"><code class="xref py py-func docutils literal notranslate"><span class="pre">setup_test_environment()</span></code></a> and setting
<a class="reference internal" href="../../ref/settings.html#std:setting-DEBUG"><code class="xref std std-setting docutils literal notranslate"><span class="pre">DEBUG</span></code></a> to <code class="docutils literal notranslate"><span class="pre">self.debug_mode</span></code> (defaults to <code class="docutils literal notranslate"><span class="pre">False</span></code>).</p>
</dd></dl>

<dl class="method">
<dt id="django.test.runner.DiscoverRunner.build_suite">
<code class="descclassname">DiscoverRunner.</code><code class="descname">build_suite</code>(<em>test_labels=None</em>, <em>extra_tests=None</em>, <em>**kwargs</em>)<a class="headerlink" href="#django.test.runner.DiscoverRunner.build_suite" title="永久链接至目标">¶</a></dt>
<dd><p>Constructs a test suite that matches the test labels provided.</p>
<p><code class="docutils literal notranslate"><span class="pre">test_labels</span></code> is a list of strings describing the tests to be run. A test
label can take one of four forms:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">path.to.test_module.TestCase.test_method</span></code> -- Run a single test method
in a test case.</li>
<li><code class="docutils literal notranslate"><span class="pre">path.to.test_module.TestCase</span></code> -- Run all the test methods in a test
case.</li>
<li><code class="docutils literal notranslate"><span class="pre">path.to.module</span></code> -- Search for and run all tests in the named Python
package or module.</li>
<li><code class="docutils literal notranslate"><span class="pre">path/to/directory</span></code> -- Search for and run all tests below the named
directory.</li>
</ul>
<p>If <code class="docutils literal notranslate"><span class="pre">test_labels</span></code> has a value of <code class="docutils literal notranslate"><span class="pre">None</span></code>, the test runner will search for
tests in all files below the current directory whose names match its
<code class="docutils literal notranslate"><span class="pre">pattern</span></code> (see above).</p>
<p><code class="docutils literal notranslate"><span class="pre">extra_tests</span></code> is a list of extra <code class="docutils literal notranslate"><span class="pre">TestCase</span></code> instances to add to the
suite that is executed by the test runner. These extra tests are run
in addition to those discovered in the modules listed in <code class="docutils literal notranslate"><span class="pre">test_labels</span></code>.</p>
<p>Returns a <code class="docutils literal notranslate"><span class="pre">TestSuite</span></code> instance ready to be run.</p>
</dd></dl>

<dl class="method">
<dt id="django.test.runner.DiscoverRunner.setup_databases">
<code class="descclassname">DiscoverRunner.</code><code class="descname">setup_databases</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.test.runner.DiscoverRunner.setup_databases" title="永久链接至目标">¶</a></dt>
<dd><p>Creates the test databases by calling
<a class="reference internal" href="#django.test.utils.setup_databases" title="django.test.utils.setup_databases"><code class="xref py py-func docutils literal notranslate"><span class="pre">setup_databases()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="django.test.runner.DiscoverRunner.run_checks">
<code class="descclassname">DiscoverRunner.</code><code class="descname">run_checks</code>(<em>databases</em>)<a class="headerlink" href="#django.test.runner.DiscoverRunner.run_checks" title="永久链接至目标">¶</a></dt>
<dd><p>Runs the <a class="reference internal" href="../checks.html"><span class="doc">system checks</span></a> on the test <code class="docutils literal notranslate"><span class="pre">databases</span></code>.</p>
<div class="versionadded">
<span class="title">New in Django 3.1:</span> <p>The <code class="docutils literal notranslate"><span class="pre">databases</span></code> parameter was added.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="django.test.runner.DiscoverRunner.run_suite">
<code class="descclassname">DiscoverRunner.</code><code class="descname">run_suite</code>(<em>suite</em>, <em>**kwargs</em>)<a class="headerlink" href="#django.test.runner.DiscoverRunner.run_suite" title="永久链接至目标">¶</a></dt>
<dd><p>Runs the test suite.</p>
<p>Returns the result produced by the running the test suite.</p>
</dd></dl>

<dl class="method">
<dt id="django.test.runner.DiscoverRunner.get_test_runner_kwargs">
<code class="descclassname">DiscoverRunner.</code><code class="descname">get_test_runner_kwargs</code>()<a class="headerlink" href="#django.test.runner.DiscoverRunner.get_test_runner_kwargs" title="永久链接至目标">¶</a></dt>
<dd><p>Returns the keyword arguments to instantiate the
<code class="docutils literal notranslate"><span class="pre">DiscoverRunner.test_runner</span></code> with.</p>
</dd></dl>

<dl class="method">
<dt id="django.test.runner.DiscoverRunner.teardown_databases">
<code class="descclassname">DiscoverRunner.</code><code class="descname">teardown_databases</code>(<em>old_config</em>, <em>**kwargs</em>)<a class="headerlink" href="#django.test.runner.DiscoverRunner.teardown_databases" title="永久链接至目标">¶</a></dt>
<dd><p>Destroys the test databases, restoring pre-test conditions by calling
<a class="reference internal" href="#django.test.utils.teardown_databases" title="django.test.utils.teardown_databases"><code class="xref py py-func docutils literal notranslate"><span class="pre">teardown_databases()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="django.test.runner.DiscoverRunner.teardown_test_environment">
<code class="descclassname">DiscoverRunner.</code><code class="descname">teardown_test_environment</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.test.runner.DiscoverRunner.teardown_test_environment" title="永久链接至目标">¶</a></dt>
<dd><p>Restores the pre-test environment.</p>
</dd></dl>

<dl class="method">
<dt id="django.test.runner.DiscoverRunner.suite_result">
<code class="descclassname">DiscoverRunner.</code><code class="descname">suite_result</code>(<em>suite</em>, <em>result</em>, <em>**kwargs</em>)<a class="headerlink" href="#django.test.runner.DiscoverRunner.suite_result" title="永久链接至目标">¶</a></dt>
<dd><p>Computes and returns a return code based on a test suite, and the result
from that test suite.</p>
</dd></dl>

</div>
</div>
<div class="section" id="s-testing-utilities">
<span id="testing-utilities"></span><h3>Testing utilities<a class="headerlink" href="#testing-utilities" title="永久链接至标题">¶</a></h3>
<div class="section" id="s-module-django.test.utils">
<span id="s-django-test-utils"></span><span id="module-django.test.utils"></span><span id="django-test-utils"></span><h4><code class="docutils literal notranslate"><span class="pre">django.test.utils</span></code><a class="headerlink" href="#module-django.test.utils" title="永久链接至标题">¶</a></h4>
<p>To assist in the creation of your own test runner, Django provides a number of
utility methods in the <code class="docutils literal notranslate"><span class="pre">django.test.utils</span></code> module.</p>
<dl class="function">
<dt id="django.test.utils.setup_test_environment">
<code class="descname">setup_test_environment</code>(<em>debug=None</em>)<a class="headerlink" href="#django.test.utils.setup_test_environment" title="永久链接至目标">¶</a></dt>
<dd><p>Performs global pre-test setup, such as installing instrumentation for the
template rendering system and setting up the dummy email outbox.</p>
<p>If <code class="docutils literal notranslate"><span class="pre">debug</span></code> isn't <code class="docutils literal notranslate"><span class="pre">None</span></code>, the <a class="reference internal" href="../../ref/settings.html#std:setting-DEBUG"><code class="xref std std-setting docutils literal notranslate"><span class="pre">DEBUG</span></code></a> setting is updated to its
value.</p>
</dd></dl>

<dl class="function">
<dt id="django.test.utils.teardown_test_environment">
<code class="descname">teardown_test_environment</code>()<a class="headerlink" href="#django.test.utils.teardown_test_environment" title="永久链接至目标">¶</a></dt>
<dd><p>Performs global post-test teardown, such as removing instrumentation from
the template system and restoring normal email services.</p>
</dd></dl>

<dl class="function">
<dt id="django.test.utils.setup_databases">
<code class="descname">setup_databases</code>(<em>verbosity</em>, <em>interactive</em>, <em>*</em>, <em>time_keeper=None</em>, <em>keepdb=False</em>, <em>debug_sql=False</em>, <em>parallel=0</em>, <em>aliases=None</em>, <em>**kwargs</em>)<a class="headerlink" href="#django.test.utils.setup_databases" title="永久链接至目标">¶</a></dt>
<dd><p>Creates the test databases.</p>
<p>Returns a data structure that provides enough detail to undo the changes
that have been made. This data will be provided to the
<a class="reference internal" href="#django.test.utils.teardown_databases" title="django.test.utils.teardown_databases"><code class="xref py py-func docutils literal notranslate"><span class="pre">teardown_databases()</span></code></a> function at the conclusion of testing.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">aliases</span></code> argument determines which <a class="reference internal" href="../../ref/settings.html#std:setting-DATABASES"><code class="xref std std-setting docutils literal notranslate"><span class="pre">DATABASES</span></code></a> aliases test
databases should be setup for. If it's not provided, it defaults to all of
<a class="reference internal" href="../../ref/settings.html#std:setting-DATABASES"><code class="xref std std-setting docutils literal notranslate"><span class="pre">DATABASES</span></code></a> aliases.</p>
<div class="versionchanged">
<span class="title">Changed in Django 3.2:</span> <p>The <code class="docutils literal notranslate"><span class="pre">time_keeper</span></code> kwarg was added, and all kwargs were made
keyword-only.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="django.test.utils.teardown_databases">
<code class="descname">teardown_databases</code>(<em>old_config</em>, <em>parallel=0</em>, <em>keepdb=False</em>)<a class="headerlink" href="#django.test.utils.teardown_databases" title="永久链接至目标">¶</a></dt>
<dd><p>Destroys the test databases, restoring pre-test conditions.</p>
<p><code class="docutils literal notranslate"><span class="pre">old_config</span></code> is a data structure defining the changes in the database
configuration that need to be reversed. It's the return value of the
<a class="reference internal" href="#django.test.utils.setup_databases" title="django.test.utils.setup_databases"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setup_databases()</span></code></a> method.</p>
</dd></dl>

</div>
<div class="section" id="s-django-db-connection-creation">
<span id="django-db-connection-creation"></span><h4><code class="docutils literal notranslate"><span class="pre">django.db.connection.creation</span></code><a class="headerlink" href="#django-db-connection-creation" title="永久链接至标题">¶</a></h4>
<p>The creation module of the database backend also provides some utilities that
can be useful during testing.</p>
<dl class="function">
<dt id="django.db.connection.creation.create_test_db">
<code class="descname">create_test_db</code>(<em>verbosity=1</em>, <em>autoclobber=False</em>, <em>serialize=True</em>, <em>keepdb=False</em>)<a class="headerlink" href="#django.db.connection.creation.create_test_db" title="永久链接至目标">¶</a></dt>
<dd><p>Creates a new test database and runs <code class="docutils literal notranslate"><span class="pre">migrate</span></code> against it.</p>
<p><code class="docutils literal notranslate"><span class="pre">verbosity</span></code> has the same behavior as in <code class="docutils literal notranslate"><span class="pre">run_tests()</span></code>.</p>
<p><code class="docutils literal notranslate"><span class="pre">autoclobber</span></code> describes the behavior that will occur if a
database with the same name as the test database is discovered:</p>
<ul class="simple">
<li>If <code class="docutils literal notranslate"><span class="pre">autoclobber</span></code> is <code class="docutils literal notranslate"><span class="pre">False</span></code>, the user will be asked to
approve destroying the existing database. <code class="docutils literal notranslate"><span class="pre">sys.exit</span></code> is
called if the user does not approve.</li>
<li>If autoclobber is <code class="docutils literal notranslate"><span class="pre">True</span></code>, the database will be destroyed
without consulting the user.</li>
</ul>
<p><code class="docutils literal notranslate"><span class="pre">serialize</span></code> determines if Django serializes the database into an
in-memory JSON string before running tests (used to restore the database
state between tests if you don't have transactions). You can set this to
<code class="docutils literal notranslate"><span class="pre">False</span></code> to speed up creation time if you don't have any test classes
with <a class="reference internal" href="overview.html#test-case-serialized-rollback"><span class="std std-ref">serialized_rollback=True</span></a>.</p>
<p>If you are using the default test runner, you can control this with the
the <a class="reference internal" href="../../ref/settings.html#std:setting-TEST_SERIALIZE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SERIALIZE</span></code></a> entry in the <a class="reference internal" href="../../ref/settings.html#std:setting-DATABASE-TEST"><code class="xref std std-setting docutils literal notranslate"><span class="pre">TEST</span></code></a> dictionary.</p>
<p><code class="docutils literal notranslate"><span class="pre">keepdb</span></code> determines if the test run should use an existing
database, or create a new one. If <code class="docutils literal notranslate"><span class="pre">True</span></code>, the existing
database will be used, or created if not present. If <code class="docutils literal notranslate"><span class="pre">False</span></code>,
a new database will be created, prompting the user to remove
the existing one, if present.</p>
<p>Returns the name of the test database that it created.</p>
<p><code class="docutils literal notranslate"><span class="pre">create_test_db()</span></code> has the side effect of modifying the value of
<a class="reference internal" href="../../ref/settings.html#std:setting-NAME"><code class="xref std std-setting docutils literal notranslate"><span class="pre">NAME</span></code></a> in <a class="reference internal" href="../../ref/settings.html#std:setting-DATABASES"><code class="xref std std-setting docutils literal notranslate"><span class="pre">DATABASES</span></code></a> to match the name of the test
database.</p>
</dd></dl>

<dl class="function">
<dt id="django.db.connection.creation.destroy_test_db">
<code class="descname">destroy_test_db</code>(<em>old_database_name</em>, <em>verbosity=1</em>, <em>keepdb=False</em>)<a class="headerlink" href="#django.db.connection.creation.destroy_test_db" title="永久链接至目标">¶</a></dt>
<dd><p>Destroys the database whose name is the value of <a class="reference internal" href="../../ref/settings.html#std:setting-NAME"><code class="xref std std-setting docutils literal notranslate"><span class="pre">NAME</span></code></a> in
<a class="reference internal" href="../../ref/settings.html#std:setting-DATABASES"><code class="xref std std-setting docutils literal notranslate"><span class="pre">DATABASES</span></code></a>, and sets <a class="reference internal" href="../../ref/settings.html#std:setting-NAME"><code class="xref std std-setting docutils literal notranslate"><span class="pre">NAME</span></code></a> to the value of
<code class="docutils literal notranslate"><span class="pre">old_database_name</span></code>.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">verbosity</span></code> argument has the same behavior as for
<a class="reference internal" href="#django.test.runner.DiscoverRunner" title="django.test.runner.DiscoverRunner"><code class="xref py py-class docutils literal notranslate"><span class="pre">DiscoverRunner</span></code></a>.</p>
<p>If the <code class="docutils literal notranslate"><span class="pre">keepdb</span></code> argument is <code class="docutils literal notranslate"><span class="pre">True</span></code>, then the connection to the
database will be closed, but the database will not be destroyed.</p>
</dd></dl>

</div>
</div>
</div>
<div class="section" id="s-integration-with-coverage-py">
<span id="s-topics-testing-code-coverage"></span><span id="integration-with-coverage-py"></span><span id="topics-testing-code-coverage"></span><h2>Integration with <code class="docutils literal notranslate"><span class="pre">coverage.py</span></code><a class="headerlink" href="#integration-with-coverage-py" title="永久链接至标题">¶</a></h2>
<p>Code coverage describes how much source code has been tested. It shows which
parts of your code are being exercised by tests and which are not. It's an
important part of testing applications, so it's strongly recommended to check
the coverage of your tests.</p>
<p>Django can be easily integrated with <a class="reference external" href="https://coverage.readthedocs.io/">coverage.py</a>, a tool for measuring code
coverage of Python programs. First, <a class="reference external" href="https://pypi.org/project/coverage/">install coverage.py</a>. Next, run the
following from your project folder containing <code class="docutils literal notranslate"><span class="pre">manage.py</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">coverage</span> <span class="n">run</span> <span class="o">--</span><span class="n">source</span><span class="o">=</span><span class="s1">&#39;.&#39;</span> <span class="n">manage</span><span class="o">.</span><span class="n">py</span> <span class="n">test</span> <span class="n">myapp</span>
</pre></div>
</div>
<p>This runs your tests and collects coverage data of the executed files in your
project. You can see a report of this data by typing following command:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">coverage</span> <span class="n">report</span>
</pre></div>
</div>
<p>Note that some Django code was executed while running tests, but it is not
listed here because of the <code class="docutils literal notranslate"><span class="pre">source</span></code> flag passed to the previous command.</p>
<p>For more options like annotated HTML listings detailing missed lines, see the
<a class="reference external" href="https://coverage.readthedocs.io/">coverage.py</a> docs.</p>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Advanced testing topics</a><ul>
<li><a class="reference internal" href="#the-request-factory">The request factory</a><ul>
<li><a class="reference internal" href="#example">Example</a></li>
<li><a class="reference internal" href="#asyncrequestfactory">AsyncRequestFactory</a></li>
</ul>
</li>
<li><a class="reference internal" href="#testing-class-based-views">Testing class-based views</a></li>
<li><a class="reference internal" href="#tests-and-multiple-host-names">Tests and multiple host names</a></li>
<li><a class="reference internal" href="#tests-and-multiple-databases">Tests and multiple databases</a><ul>
<li><a class="reference internal" href="#testing-primary-replica-configurations">Testing primary/replica configurations</a></li>
<li><a class="reference internal" href="#controlling-creation-order-for-test-databases">Controlling creation order for test databases</a></li>
</ul>
</li>
<li><a class="reference internal" href="#advanced-features-of-transactiontestcase">Advanced features of <code class="docutils literal notranslate"><span class="pre">TransactionTestCase</span></code></a></li>
<li><a class="reference internal" href="#enforce-running-test-classes-sequentially">Enforce running test classes sequentially</a></li>
<li><a class="reference internal" href="#using-the-django-test-runner-to-test-reusable-applications">Using the Django test runner to test reusable applications</a></li>
<li><a class="reference internal" href="#using-different-testing-frameworks">Using different testing frameworks</a><ul>
<li><a class="reference internal" href="#defining-a-test-runner">Defining a test runner</a><ul>
<li><a class="reference internal" href="#attributes">Attributes</a></li>
<li><a class="reference internal" href="#methods">Methods</a></li>
</ul>
</li>
<li><a class="reference internal" href="#testing-utilities">Testing utilities</a><ul>
<li><a class="reference internal" href="#module-django.test.utils"><code class="docutils literal notranslate"><span class="pre">django.test.utils</span></code></a></li>
<li><a class="reference internal" href="#django-db-connection-creation"><code class="docutils literal notranslate"><span class="pre">django.db.connection.creation</span></code></a></li>
</ul>
</li>
</ul>
</li>
<li><a class="reference internal" href="#integration-with-coverage-py">Integration with <code class="docutils literal notranslate"><span class="pre">coverage.py</span></code></a></li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="tools.html"
                        title="上一章">Testing tools</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="../auth/index.html"
                        title="下一章">User authentication in Django</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../../_sources/topics/testing/advanced.txt"
            rel="nofollow">显示源代码</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>快速搜索</h3>
    <div class="searchformwrapper">
    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="转向" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">7月 23, 2021</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="tools.html" title="Testing tools">previous</a>
     |
    <a href="../index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="../auth/index.html" title="User authentication in Django">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>